from typing import List
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, Form
from fastapi.responses import JSONResponse
from ...services.oss_service import get_oss_service, OSSService
from ...core.auth import get_current_user
from ...schemas.user import User
import logging

logger = logging.getLogger(__name__)

router = APIRouter()

@router.post("/upload/avatar")
async def upload_avatar(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user),
    oss_service: OSSService = Depends(get_oss_service)
):
    try:
        # 验证文件类型
        if not file.content_type.startswith('image/'):
            raise HTTPException(
                status_code=400,
                detail="只能上传图片文件"
            )
        
        # 上传到OSS
        file_key, file_url = await oss_service.upload_file(
            file=file,
            file_type="avatars",
            validate=True
        )
        
        return {
            "code": 200,
            "message": "头像上传成功",
            "data": {
                "file_key": file_key,
                "file_url": file_url,
                "filename": file.filename
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"头像上传失败: {e}")
        raise HTTPException(status_code=500, detail="头像上传失败")

@router.post("/upload/audio")
async def upload_audio(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user),
    oss_service: OSSService = Depends(get_oss_service)
):
    try:
        # 验证文件类型
        allowed_audio_types = [
            'audio/mpeg', 'audio/mp3', 'audio/wav', 
            'audio/ogg', 'audio/webm', 'audio/m4a'
        ]
        if file.content_type not in allowed_audio_types:
            raise HTTPException(
                status_code=400,
                detail="只能上传音频文件 (mp3, wav, ogg, webm, m4a)"
            )
        
        # 上传到OSS
        file_key, file_url = await oss_service.upload_file(
            file=file,
            file_type="audio",
            validate=True
        )
        
        return {
            "code": 200,
            "message": "音频上传成功",
            "data": {
                "file_key": file_key,
                "file_url": file_url,
                "filename": file.filename
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"音频上传失败: {e}")
        raise HTTPException(status_code=500, detail="音频上传失败")

@router.post("/upload/image")
async def upload_image(
    file: UploadFile = File(...),
    image_type: str = Form(default="general"),  # avatars, covers, general
    current_user: User = Depends(get_current_user),
    oss_service: OSSService = Depends(get_oss_service)
):
    try:
        # 验证文件类型
        if not file.content_type.startswith('image/'):
            raise HTTPException(
                status_code=400,
                detail="只能上传图片文件"
            )
        
        # 根据图片类型设置存储路径
        file_type = f"images/{image_type}" if image_type != "general" else "images"
        
        # 上传到OSS
        file_key, file_url = await oss_service.upload_file(
            file=file,
            file_type=file_type,
            validate=True
        )
        
        return {
            "code": 200,
            "message": "图片上传成功",
            "data": {
                "file_key": file_key,
                "file_url": file_url,
                "filename": file.filename,
                "image_type": image_type
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"图片上传失败: {e}")
        raise HTTPException(status_code=500, detail="图片上传失败")

@router.post("/upload/batch")
async def upload_batch_files(
    files: List[UploadFile] = File(...),
    file_type: str = Form(default="general"),
    current_user: User = Depends(get_current_user),
    oss_service: OSSService = Depends(get_oss_service)
):
    if len(files) > 10:
        raise HTTPException(
            status_code=400,
            detail="一次最多只能上传10个文件"
        )
    
    results = []
    failed_files = []
    
    for file in files:
        try:
            file_key, file_url = await oss_service.upload_file(
                file=file,
                file_type=file_type,
                validate=True
            )
            
            results.append({
                "filename": file.filename,
                "file_key": file_key,
                "file_url": file_url,
                "status": "success"
            })
            
        except Exception as e:
            failed_files.append({
                "filename": file.filename,
                "error": str(e),
                "status": "failed"
            })
            logger.error(f"文件 {file.filename} 上传失败: {e}")
    
    return {
        "code": 200,
        "message": f"批量上传完成，成功 {len(results)} 个，失败 {len(failed_files)} 个",
        "data": {
            "success_count": len(results),
            "failed_count": len(failed_files),
            "successful_files": results,
            "failed_files": failed_files
        }
    }

@router.delete("/upload/{file_key:path}")
async def delete_file(
    file_key: str,
    current_user: User = Depends(get_current_user),
    oss_service: OSSService = Depends(get_oss_service)
):
    try:
        success = oss_service.delete_file(file_key)
        
        if success:
            return {
                "code": 200,
                "message": "文件删除成功",
                "data": {"file_key": file_key}
            }
        else:
            raise HTTPException(status_code=500, detail="文件删除失败")
            
    except Exception as e:
        logger.error(f"文件删除失败: {e}")
        raise HTTPException(status_code=500, detail="文件删除失败")

@router.get("/upload/signed-url/{file_key:path}")
async def get_signed_url(
    file_key: str,
    expires: int = 3600,
    current_user: User = Depends(get_current_user),
    oss_service: OSSService = Depends(get_oss_service)
):
    try:
        signed_url = oss_service.get_file_url(file_key, expires)
        
        return {
            "code": 200,
            "message": "获取签名URL成功",
            "data": {
                "file_key": file_key,
                "signed_url": signed_url,
                "expires_in": expires
            }
        }
        
    except Exception as e:
        logger.error(f"获取签名URL失败: {e}")
        raise HTTPException(status_code=500, detail="获取签名URL失败") 